﻿using System;
using System.Collections.Generic;
using System.Text;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Configuration;
using System.IO;
using System.Web.Core;

namespace Yuanlin.Business
{
    public class ContentHtmlAddControl : YuanlinUserControl,
        IReplyConverter<ContentHtmlCategoryReply, GetListOperation>
    {
        protected ValuedTextBox titleValuedTextBox;
        protected ValuedDropDownList categoryDropDownList;
        protected ValuedEditor descriptionValuedEditor;

        protected IButton SaveButton;
        protected IButton BackButton;
        private EntityList categories;

        public override void GetRequests(List<BaseRequestBinder> requestBinders)
        {
            requestBinders.Add(RequestHelper.BuildGetContentHtmlCategoryListRequest(this));
        }

        protected override void OnLoad(EventArgs e)
        {
            SaveButton.Click += new EventHandler(SaveButton_Click);
            BackButton.Click += new EventHandler(BackButton_Click);
        }

        public void BackButton_Click(object sender, EventArgs e)
        {
            Page.Response.Redirect(SiteUrls.Instance().GetContentHtmlListUrl());
        }

        public void SaveButton_Click(object sender, EventArgs e)
        {
            ContentHtml contentHtml = new ContentHtml();
            
            contentHtml.Title.Value =  CensorWordManager.CensorWord(this.titleValuedTextBox.Value);
            contentHtml.Body.Value =  CensorWordManager.CensorWord(this.descriptionValuedEditor.Value);
            contentHtml.CategoryId.Value = int.Parse(categoryDropDownList.Value);

            if (BusinessManager.CreateContentHtml(contentHtml) == -2)
            {
                Globals.ShowMessage(this.Page, "添加失败", "此信息已经存在！");
                return;
            }

            Page.Response.Redirect(SiteUrls.Instance().GetContentHtmlListUrl());
        }

        private void Bind()
        {
            categoryDropDownList.DataSource = categories;
            categoryDropDownList.DataValueField = "EntityId";
            categoryDropDownList.DataTextField = "Title";
            categoryDropDownList.DataBind();
        }

        #region IReplyConverter<ContentHtmlCategoryReply,GetListOperation> Members

        public void ConvertReply(ContentHtmlCategoryReply reply, GetListOperation operation)
        {
           categories = reply.EntityList;

           if (!Page.IsPostBack)
           {
               Bind();
           }
        }

        #endregion
    }
}